package com.mike.filter;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import java.util.Iterator;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Description 防暴刷
 * @Date 2021/11/30 16:32
 * @Created by mike
 */
@Component
public class LimitFilter  implements GlobalFilter, Ordered {

    private static final Map<String, ConcurrentHashMap.KeySetView<Long,Boolean>> ipMap = new ConcurrentHashMap<>();

    @Value("${limit.time}")
    private int time;

    @Value("${limit.number}")
    private int number;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        String path = request.getPath().toString();
        if (path.startsWith("/api/user/register")){
            String hostString = Objects.requireNonNull(request.getRemoteAddress()).getHostString();
            if (ipMap.containsKey(hostString)){
                ConcurrentHashMap.KeySetView<Long, Boolean> keySetView = ipMap.get(hostString);
                Iterator<Long> iterator = keySetView.iterator();
                long current = System.currentTimeMillis();
                int requestCount = 0;
                while (iterator.hasNext()) {
                    Long next = iterator.next();
                    if ((current - next) > time){
                        iterator.remove();
                    }else {
                        requestCount++;
                    }
                }
                if (requestCount > number){
                    response.setStatusCode(HttpStatus.FORBIDDEN);
                    String message = "您频繁进⾏注册，请求已被拒绝";
                    DataBuffer wrap = response.bufferFactory().wrap(message.getBytes(StandardCharsets.UTF_8));
                    return response.writeWith(Mono.just(wrap));
                }else {
                    keySetView.add(current);
                }
            }else {
                ConcurrentHashMap.KeySetView<Long, Boolean> keySet = ConcurrentHashMap.newKeySet();
                keySet.add(System.currentTimeMillis());
                ipMap.put(hostString,keySet);
            }
        }
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 1;
    }
}
